package iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.activity;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.R;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.activity.secondActivity.ActivityVerification;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.fragment.consumerFragment.FragmentAddTrace;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.fragment.consumerFragment.FragmentSearchTrace;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.fragment.consumerFragment.FragmentShop;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.fragment.producerFragment.FragmentAddProduct;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.fragment.producerFragment.FragmentProductManagement;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.fragment.producerFragment.FragmentProfile;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.SmsBroadcastReceiver;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceConnection.ProductServiceConnection;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceImpl.LoginService;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceImpl.ProductService;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.utils.ImageUtils;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.utils.QRCodeUtils;

public class ActivityConsumer extends AppCompatActivity {
    private BottomNavigationView bottomNavigationView;  //底部导航
    private Fragment fragment;

    // 登录相关服务类
    private ProductServiceConnection productConnection;

    @Override
    protected void onStart() {
        super.onStart();
        productConnection = new ProductServiceConnection(service -> {
            if (fragment instanceof FragmentAddTrace){
                ((FragmentAddTrace) fragment).onServiceConnected(productConnection.getService());
            }else if (fragment instanceof FragmentShop){
                ((FragmentShop) fragment).onServiceConnected(productConnection.getService());
            }
        });
        Intent intent = new Intent(this, ProductService.class);
        bindService(intent, productConnection, BIND_AUTO_CREATE);
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (productConnection.isBound()) {
            unbindService(productConnection);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_consumer);
        bottomNavigationView = findViewById(R.id.bottom_navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener(navListener);

        Integer info = getIntent().getIntExtra("targetFragment",-1);
        Log.d("Test",info + " info");
        Log.d("Test", "Intent extras: " + getIntent().getExtras());

        if (info == 2){
            fragment = new FragmentAddTrace();
        }else{
            fragment = new FragmentShop();
        }

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commitNow();


    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK && data != null) {
                Uri selectedImageUri = data.getData();
                ImageView iQRCode = new ImageView(this);
                iQRCode.setImageURI(selectedImageUri);
                QRCodeUtils.readQRCodeFromBitmap(ImageUtils.drawable2bitmap(iQRCode.getDrawable()), data1 -> {
                    if (data1 != null) {
                        SharedPreferences SharedPreferences = getSharedPreferences("SmsData",MODE_PRIVATE);
                        SharedPreferences.Editor editor = SharedPreferences.edit();
                        editor.putString("productId",data1);
                        editor.apply();

                        // 跳转到新的Activity，显示验证码输入界面
                        Intent intent = new Intent(this, ActivityVerification.class);
                        startActivity(intent);

                    } else {
                        Toast.makeText(this, "未能识别二维码重新选择", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }


    // 底部导航的监听事件
    private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment selectedFragment = null;

            int itemId = item.getItemId();


            if (itemId == R.id.search_trace) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(intent, 1); // 请求二维码
                return true;
            }

            if (itemId == R.id.nav_shop) {
                selectedFragment = new FragmentShop();
            }else if (itemId == R.id.add_trace) {
                selectedFragment = new FragmentAddTrace();
            }else if (itemId == R.id.per_info) {
                selectedFragment = new FragmentProfile();
            }
            switchToFragment(selectedFragment);

            return true;
        }
    };


    // 跳转Fragment
    private void switchToFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment)
                .commitNow();
        if (fragment instanceof FragmentAddTrace){
            ((FragmentAddTrace) fragment).onServiceConnected(productConnection.getService());
        }else if (fragment instanceof FragmentShop){
            ((FragmentShop) fragment).onServiceConnected(productConnection.getService());
        }
    }
}